package controllers

import (
	"fmt"
	"github.com/beego/beego/v2/core/validation"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/dgrijalva/jwt-go/v4"
	"net/http"
	"time"
	"user/models"
	"user/utils"
)

type LoginController struct {
	beego.Controller
}

func (c *LoginController) Login() {
	username := c.GetString("une")
	password := c.GetString("pwd")
	valid := validation.Validation{}
	valid.Required("username", username).Message("用户名不能为空")
	valid.Required("password", password).Message("密码不能为空")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			c.Data["json"] = map[string]interface{}{
				"code":    -1,
				"message": err,
			}
			c.ServeJSON()
			return
		}
	}
	data, err := models.Admin(username)
	fmt.Println(data)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    -1,
			"message": err.Error(),
		}
		c.ServeJSON()
		return
	}
	if data.Password != password {
		c.Data["json"] = map[string]interface{}{
			"code":    -1,
			"message": "密码错误",
		}
		c.ServeJSON()
		return
	}
	a := 2 * time.Minute
	b := int64(a)
	token, err := utils.CreateToken(&utils.MyCustomClaims{
		Id:       data.Id,
		Username: data.Username,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: jwt.NewTime(float64(time.Now().Unix() + b)),
		},
	})
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    http.StatusCreated,
			"message": err.Error(),
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code":    http.StatusOK,
		"message": "登陆成功",
		"data":    token,
	}
	c.ServeJSON()
	return
}
